<template>
  <div class="container">
    <img ref="imageRef" class="img" :src="image">
    <van-nav-bar left-text="取消" right-text="确定" @click-left="$emit('close')" @click-right="onConfirm" />
  </div>
</template>
<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updatePhoto, updateProfile } from '@/api/user.js'

export default {
  props: {
    file: {
      required: true
    },
    user: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      image: window.URL.createObjectURL(this.file),
      cropper: null,
      userimg: this.user
    }
  },
  mounted() {
    const image = this.$refs.imageRef
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true
    })
  },
  methods: {
    getCroppedCanvas() {
      return new Promise(resolve => {
        this.cropper.getCroppedCanvas().toBlob(file => {
          resolve(file)
        })
      })
    },
    async onConfirm() {
      this.$toast.loading({
        message: '保存中',
        forbidclick: true,
        duration: 0 // 展示时间，0 表示持续展示
      })
      const file = await this.getCroppedCanvas()
      const fd = new FormData()
      fd.append('file', file)
      const { data: res } = await updatePhoto(fd)

      this.userimg.user_img = res.url
      this.$store.commit('setProfile', this.userimg)
      await updateProfile(this.$store.state.user.id, this.userimg)
      this.$emit('close')
      this.$toast.success('保存成功')
    }
  }
}
</script>
<style lang="less" scoped>
.container {
  width: 100%;
  height: 100%;
}
.img {
  width: 100%;
  display: block;
}
.van-nav-bar {
  position: fixed;
  bottom: 0;
  width: 100%;
  left: 0;
  background-color: unset;
}
</style>
